package com.campus.customer.service;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信订阅消息服务
 * 负责向顾客发送微信订阅消息
 */
@Service
@Slf4j
public class WechatSubscribeMessageService {
    
    private static final String SEND_SUBSCRIBE_MESSAGE_URL = 
            "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s";
    
    // 订单取消通知模板ID - 从配置文件读取
    @Value("${wechat.subscribe-templates.order-cancel}")
    private String orderCancelTemplateId;
    
    // 订单完成通知模板ID - 从配置文件读取
    @Value("${wechat.subscribe-templates.order-complete}")
    private String orderCompleteTemplateId;
    
    @Autowired
    private WechatAuthService wechatAuthService;

    /**
     * 发送订单取消通知
     * @param openId 用户openId
     * @param orderId 订单号
     * @param orderAmount 订单金额
     * @param cancelReason 取消原因
     */
    public void sendOrderCancelMessage(String openId, String orderId, String orderAmount, String cancelReason) {
        try {
            String accessToken = wechatAuthService.getAccessToken();
            if (accessToken == null) {
                log.error("获取access_token失败，无法发送订单取消通知");
                return;
            }

            // 构建消息数据
            Map<String, Object> data = new HashMap<>();
            data.put("character_string1", createDataItem(orderId)); // 订单号
            data.put("amount2", createDataItem(orderAmount)); // 订单金额
            data.put("time8", createDataItem(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))); // 取消时间
            data.put("thing9", createDataItem(cancelReason)); // 取消原因
            
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("touser", openId);
            requestBody.put("template_id", orderCancelTemplateId);
            requestBody.put("data", data);
            
            // 发送请求
            String url = String.format(SEND_SUBSCRIBE_MESSAGE_URL, accessToken);
            String requestBodyJson = JSONUtil.toJsonStr(requestBody);
            String response = HttpUtil.post(url, requestBodyJson);
            
            log.info("发送订单取消通知响应: {}", response);
            
            JSONObject result = JSONUtil.parseObj(response);
            Integer errcode = result.getInt("errcode");
            if (errcode != null && errcode == 0) {
                log.info("订单取消通知发送成功，订单号: {}, 用户openId: {}", orderId, openId);
            } else {
                String errmsg = result.getStr("errmsg");
                if (errcode != null && errcode == 43101) {
                    log.warn("用户拒绝接收订单取消通知，订单号: {}, 用户openId: {}", orderId, openId);
                } else {
                    log.error("订单取消通知发送失败，订单号: {}, 错误码: {}, 错误信息: {}", orderId, errcode, errmsg);
                }
            }
        } catch (Exception e) {
            log.error("发送订单取消通知异常，订单号: {}, 用户openId: {}", orderId, openId, e);
        }
    }

    /**
     * 发送订单完成通知
     * @param openId 用户openId
     * @param orderId 订单号
     * @param goodsName 货品名称
     * @param orderAmount 订单金额
     * @param completeTime 完成时间
     * @param remark 订单备注
     */
    public void sendOrderCompleteMessage(String openId, String orderId, String goodsName, String orderAmount, String completeTime, String remark) {
        try {
            String accessToken = wechatAuthService.getAccessToken();
            if (accessToken == null) {
                log.error("获取access_token失败，无法发送订单完成通知");
                return;
            }

            // 构建消息数据
            Map<String, Object> data = new HashMap<>();
            data.put("character_string1", createDataItem(orderId)); // 订单号
            data.put("thing6", createDataItem(goodsName)); // 货品名称
            data.put("amount2", createDataItem(orderAmount)); // 订单金额
            data.put("time3", createDataItem(completeTime)); // 完成时间
            data.put("thing4", createDataItem(remark != null ? remark : "无")); // 订单备注
            
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("touser", openId);
            requestBody.put("template_id", orderCompleteTemplateId);
            requestBody.put("data", data);
            
            // 发送请求
            String url = String.format(SEND_SUBSCRIBE_MESSAGE_URL, accessToken);
            String requestBodyJson = JSONUtil.toJsonStr(requestBody);
            String response = HttpUtil.post(url, requestBodyJson);
            
            log.info("发送订单完成通知响应: {}", response);
            
            JSONObject result = JSONUtil.parseObj(response);
            Integer errcode = result.getInt("errcode");
            if (errcode != null && errcode == 0) {
                log.info("订单完成通知发送成功，订单号: {}, 用户openId: {}", orderId, openId);
            } else {
                String errmsg = result.getStr("errmsg");
                if (errcode != null && errcode == 43101) {
                    log.warn("用户拒绝接收订单完成通知，订单号: {}, 用户openId: {}", orderId, openId);
                } else {
                    log.error("订单完成通知发送失败，订单号: {}, 错误码: {}, 错误信息: {}", orderId, errcode, errmsg);
                }
            }
        } catch (Exception e) {
            log.error("发送订单完成通知异常，订单号: {}, 用户openId: {}", orderId, openId, e);
        }
    }

    /**
     * 创建消息数据项
     */
    private Map<String, String> createDataItem(String value) {
        Map<String, String> item = new HashMap<>();
        item.put("value", value);
        return item;
    }
}